package cn.gailvlun.gll.presentation.login.viewmodel

import android.databinding.ObservableField
import cn.gailvlun.gll.databinding.ActivityLoginBinding
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.base.Profile
import cn.gailvlun.gll.net.login.LoginReq
import cn.gailvlun.gll.presentation.base.BaseActivity
import cn.gailvlun.gll.presentation.login.ForgotPasswordActivity
import cn.gailvlun.gll.presentation.login.adapter.LoginType
import cn.gailvlun.gll.util.*
import com.blankj.utilcode.util.SPUtils


class LoginViewModel(val activity: BaseActivity, private val mBinding: ActivityLoginBinding) : BaseViewModel(activity) {

    val phoneNumber = ObservableField<String>("")
    fun onForgotPassword() {
        ForgotPasswordActivity.openActivity(activity)
    }

    fun onLogin() {
        login()
    }

    fun login() {
        val phoneNumber = mBinding.cetPhone.text.toString().trim()
        val pwd = mBinding.petPassword.text.toString().trim()

        if (IsEmpty.string(phoneNumber)) {
            ToastUtil.showShort("请填写手机号")
            return

        }

        if (PhoneUtil.isEmpty(pwd)) {
            ToastUtil.showShort("请填写密码")
            return
        }


        val cc = countryNameAndCode.split(" ")[1]
        val phoneNumberWithCc = "$cc$phoneNumber"
        
        val progressDialog = DialogUtil.showIndeterminate(activity)
        HttpMethods.getLoginService()
                .login(LoginReq(phoneNumberWithCc, pwd))
                .compose(RxUtil.applyScheduler())
                .subscribe(object : HttpSubscriber<Profile>() {
                    override fun onSuccess(response: Profile) {
                        
                        progressDialog.dismiss()

                        SPUtils.getInstance().put("loginType", LoginType.phone.name)
                        LoginUtil.login(activity, response)
                    }

                    override fun onFailure(errMsg: String, response: Profile?, code: Int) {
                        
                        progressDialog.dismiss()

                        DialogUtil.showError(activity, errMsg)
                    }
                })
    }

}